﻿using UnityEngine;
using System.Collections;
using AssetLoad;

[RequireComponent(typeof(UITexture))]
public class AloneTextureKit : MonoBehaviour
{
    private string path = null;
    private bool delayUnload = false;

    public void SetPath(string path,bool delayUnload = false,System.Action endCallBack=null)
    {
        var tex = GetComponent<UITexture>();
        if (this.path != null)
        {
            tex.mainTexture = null;
            ResourceLoader.GetInstance().textureLoader.UnloadTexture(this.path);
        }
        this.path = path;
        StartCoroutine(ResourceLoader.GetInstance().textureLoader.LoadTexture(path, () => {
            tex.mainTexture = ResourceLoader.GetInstance().textureLoader.GetTexture(path, CommonMethod.GetAssetNameFromAssetBundleName(path)) as Texture2D;
            if(endCallBack!=null)
            {
                endCallBack();
            }
        }));
        this.delayUnload = delayUnload;
    }

    public void OnDisable()
    {
        if(!delayUnload)
        {
            UnloadResource();
        }
    }

    public void OnDestroy()
    {
        UnloadResource();
    }

    public void UnloadResource()
    {
        if (path != null)
        {
            StopAllCoroutines();
            var tex = GetComponent<UITexture>();
            tex.mainTexture = null;
            ResourceLoader.GetInstance().textureLoader.UnloadTexture(path);
            path = null;
        }
    }
}
